
var lastSubmission = new Date().getTime();
var lastUpdate = new Date().getTime() - 500;

var inGame = -1;


function externalLinks() {
  if (!document.getElementsByTagName) return;
  var anchors = document.getElementsByTagName("a");
  for (var i=0; i<anchors.length; i++) {
    var anchor = anchors[i];
    if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
      anchor.target = "_blank";
    }
  }
}

function GetXmlHttpObject()
{
  var xmlHttp=null;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
  return xmlHttp;
}

function ajaxFunction(url, postFields, postData, completeFunction)
{
  xmlHttp = GetXmlHttpObject();
  if (xmlHttp==null) {
    alert ("Your browser does not support AJAX!");
    return;
  } 

  // Generate full URL:
  if (postFields.length != postData.length) {
    alert ("Post data inconsistant!");
    return;
  }
  
  if (postFields.length > 0) {
    url=url+"?&";
    for (var itemCount = 0; itemCount < postFields.length; itemCount ++) {
      url=url+postFields[itemCount] + "=" + postData[itemCount] + "&";
    }
  }
  
  xmlHttp.onreadystatechange = completeFunction;
  xmlHttp.setRequestHeader('Content-Type', 'text/xml');
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}

function postMessage(user, message) {
  // Start a new ajax request
  var fieldValue = new Array('newmessage', 'user', 'message');
  var dataValue = new Array('true', user, message);
  
  var messageComplete;
  
  ajaxFunction('include/lobbyControl.php', fieldValue, dataValue, messageComplete = function() {  
      if(xmlHttp.readyState==4) {
        displayNewMessage(xmlHttp.responseText);
      }
    });
}

// fullmessage should be a all that will be in the list element containng the message!
function displayNewMessage(fullmessage) {
  var lobbyChatUl = document.getElementById('lobbyChatUl');
  var lobbyMessages = lobbyChatUl.childNodes;
  var newMessage = document.createElement("li");
  newMessage.innerHTML = fullmessage;
  
  lobbyChatUl.appendChild(newMessage);
  
  var lobbyDiv = document.getElementById('lobbyList');
  lobbyDiv.scrollTop = lobbyDiv.scrollHeight;
}

function clearUserList() {
  //alert("clearUserList::in");
  var userList = document.getElementById("userListUl")
  while (userList.childNodes.length >2) {
    userList.removeChild(userList.lastChild);
  }
  //alert("clearUserList::out");
}

function addUser(username) {
  //alert("addUser::in");
  var listNode = document.createElement("li");
  listNode.appendChild(document.createTextNode(username));
  document.getElementById("userListUl").appendChild(listNode); 
}

function clearGameList() {
  //alert("clearGameList::in");
  var gameTable = document.getElementById("gamesTable");
  var rows = gameTable.getElementsByTagName("tr");
  
  while (gameTable.getElementsByTagName("tr").length >1) {
    gameTable.deleteRow(gameTable.getElementsByTagName("tr").length - 1);
  }

  //alert("clearGameList::out");
}

function displayPlayers(players, maxPlayers) {
  return players + "/" + maxPlayers;
}

function displayProgress(value) {
  if (parseInt(value) == 1) {
    return "True";
  } else {
    return "False";
  }
}

function displayJoinLink(gameId) {
  return '<span onclick="joinGame('+gameId+')">Join</span>';
}

function addGame(id, name, host, players, maxPlayers, map, inProgress) {
  //alert("addGame::in");
  var gameTable = document.getElementById("gamesTable");
  var tableRows = gameTable.getElementsByTagName("tr");
  var gameRow = gameTable.insertRow(tableRows.length);
  
  var nameCell = gameRow.insertCell(0);
    nameCell.innerHTML = name;
    nameCell.className = "gameName";
  var hostCell = gameRow.insertCell(1).innerHTML = host;
  var playersCell = gameRow.insertCell(2).innerHTML =  displayPlayers(players, maxPlayers);
  var inProgressCell = gameRow.insertCell(3).innerHTML = displayProgress(inProgress);
  var linkCell = gameRow.insertCell(4).innerHTML = displayJoinLink(id);
}

function setNoGames() {
  //alert("setNoGames::IN::");
  var gameTable = document.getElementById("gamesTable");
  var gameRow = gameTable.insertRow(1);
  
  var newCell = gameRow.insertCell(0);
  newCell.innerHTML = "No active games";
  newCell.colSpan = "5";
}

function submitMessage(form) {
  var now = new Date().getTime();
  //alert(lastSubmission + " :: " + now);
  if (lastSubmission < (now - 600)) {
    // Get username and message
    var user = form.username.value;
    var message = form.msg.value;
    
    if (message !="") {
      form.msg.value = "";
      postMessage(user, message);
      lastSubmission = new Date().getTime();
    }
  } else { 
    alert ("Message submission too soon, please give more time in between posts.");
  }
}

function updateLobby() {
  var now = new Date().getTime();
  if (lastUpdate < (now - 300)) {
    // Get username and message
    var user = document.getElementById('username').value;
    
    pollServer(user);
  } else { 
    alert ("Update submission too soon, please give more time in between updates.");
  }
  lastUpdate = new Date().getTime();
}

function pollServer(user) {
  var fieldValue = new Array('lobbypoll', 'user');
  var dataValue = new Array('true', user);
  
  var pollComplete;

  ajaxFunction('include/lobbyControl.php', fieldValue, dataValue, pollComplete = function() {  
    if(xmlHttp.readyState==4) {
        parseXMLresponse(xmlHttp.responseXML);
      }
    });
}

// Parses all the current lobby details this includes:
/*    messages
/*    users
/*    games
*/
function parseXMLresponse(responseXML) {
  //alert("parseXMLresponse::IN::" + xmlHttp.responseXML);
  xmlDoc = responseXML;
  
  if (xmlDoc) {
    xmlDoc = xmlDoc.getElementsByTagName("xml")[0];
    
    xmlMessages = xmlDoc.getElementsByTagName("lobbymessages");
    if (xmlMessages[0]) {
      xmlMessages = xmlMessages[0].getElementsByTagName("message");
      // Loop through the messages
      for (var msgCount = 0; msgCount < xmlMessages.length; msgCount++) {
        var dateSpan = "<span class=\"postDate\">(" + xmlMessages[msgCount].getElementsByTagName("posted")[0].childNodes[0].nodeValue + ")</span> ";
        var username = "<em class=\"usernameem\">" + xmlMessages[msgCount].getElementsByTagName("username")[0].childNodes[0].nodeValue + "</em>: ";
        var message = xmlMessages[msgCount].getElementsByTagName("text")[0].childNodes[0].nodeValue;
        
        //message = formatBBCode(message);
        displayNewMessage(dateSpan + username + message);
      }
    }
    
    xmlUsers = xmlDoc.getElementsByTagName("lobbyusers");
    if (xmlUsers[0]) {
      xmlUsers = xmlUsers[0].getElementsByTagName("user");
      clearUserList();
      for (var usrCount = 0; usrCount < xmlUsers.length; usrCount ++) {
        var username = xmlUsers[usrCount].getElementsByTagName("name")[0].childNodes[0].nodeValue;
        addUser(username);
      }
    }
    
    xmlGames = xmlDoc.getElementsByTagName("lobbygames");
    if (xmlGames[0]) {
      xmlGames = xmlGames[0].getElementsByTagName("game");
      clearGameList();
      for (var gameCount = 0; gameCount < xmlGames.length; gameCount ++) {
        var id = xmlGames[gameCount].getElementsByTagName("id")[0].childNodes[0].nodeValue;
        var name = xmlGames[gameCount].getElementsByTagName("name")[0].childNodes[0].nodeValue;
        var host = xmlGames[gameCount].getElementsByTagName("player1")[0].childNodes[0].nodeValue;
        var players = xmlGames[gameCount].getElementsByTagName("ingame")[0].childNodes[0].nodeValue;
        var maxPlayers = xmlGames[gameCount].getElementsByTagName("maxplayers")[0].childNodes[0].nodeValue;
        var map = xmlGames[gameCount].getElementsByTagName("map")[0].childNodes[0].nodeValue;
        var inProgress = xmlGames[gameCount].getElementsByTagName("inprogress")[0].childNodes[0].nodeValue;
        
        addGame(id, name, host, players, maxPlayers, map, inProgress);
      }
    } else {
      clearGameList();
      setNoGames();
    }
  }
  
  // Update again in 1 second.
  setTimeout("updateLobby()", 1000);
}

function joinGame(gameId) {
  //alert("joinGame::IN");
  
  var user = document.getElementById('username').value;
  var fieldValue = new Array('joingame', 'user');
  var dataValue = new Array(gameId, user);

  var joinComplete;

  ajaxFunction('include/lobbyControl.php', fieldValue, dataValue, joinComplete = function() {  
    if(xmlHttp.readyState==4) {
        parseXMLJoinResponse(xmlHttp.responseText);
      }
    });
}

function parseXMLJoinResponse(messageResponse) {
  //alert("parseXMLJoinResponse::IN::" + messageResponse);
  var reply = messageResponse;
  
  reply = reply.split(":");
  
  if (reply[0] == "joined") {
    joinedGame(reply[1]);
  } else {
    alert("Unable to join game: " + reply[1]);
  }
}

function joinedGame(gameId) {
  //alert("joinedGame::IN::" + gameId);
  gameOptions = document.getElementById('gameOptions');
  gameOptions.innerHTML = '<form action="index.php" method="post"><input type="hidden" name="gameId" value="'+gameId+'"><input type="submit" name="leaveGame" value="Leave Game"></form>';
  inGame = gameId;
}

function createGame() {
  //alert("update");
  return true;
}


function formatBBCode(message) {
  message.replace("[b]", "<b>");
  message.replace("[/b]", "</b>");
  message.replace("[i]", "<i>");
  message.replace("[/i]", "</i>");

  return message;
}

window.onload = startLobby;

function startLobby() {
  setTimeout("updateLobby()", 1000);
}
